<?php
/**
 * Generates pagination numbers, determines number of pages and generates offsets for query statements
 */
class Paginize
{
    public $firstOffset = 0;
    public $previousOffset;
    public $currentOffset;
    public $nextOffset;
    public $lastOffset;
    public $offsets = array();
    public $totalPages;
    public $pages = array();
    public $firstPage = 1;
    public $previousPage;
    public $nextPage;
    public $lastPage;
    
    
    public function __construct($total, $page, $limit, $range = 0)
    {
        if ($total <= 0)
            return false;

        $this->totalPages = round($total / $limit);

        if ($this->totalPages * $limit < $total)
            $this->totalPages++;

        $this->lastPage = $this->totalPages;

        if ($page > $this->totalPages)
            $page = $this->totalPages;

        for ($i = 1; $i <= $this->totalPages; $i++) {
            $this->offsets[] = ($limit * $i) - $limit;
        }
        
        $this->lastOffset     = $this->offsets[$this->totalPages - 1];
        $this->previousOffset = ($page - 2) <= 0 ? 0 : $this->offsets[$page - 2];
        $this->currentOffset  = $this->offsets[$page - 1];
        $this->nextOffset     = isset($this->offsets[$page]) ? $this->offsets[$page] : $this->lastOffset;
        
        if ($range > 0) {
            if ($range >= $this->totalPages) {
                $last  = $this->totalPages;
                $start = 1;
            } else {
                $distanceToLast  = $this->totalPages - $page;
                $distanceToFirst = ($page - 1) <= 0 ? 0 : $page - 1;

                if ($range % 2 > 0) {
                    $half = ($range - 1) / 2;
                } else {
                    $half = $range / 2;
                }
                
                if ($distanceToLast <= $half) {
                    $start  = $page - ($this->totalPages - $half);
                    $start += $half;
                    $start  = $page - $start;
                } else if ($distanceToFirst <= $half) {
                    $start = 1;
                } else {
                    $start = $page - $half;
                }
                
                $last = ($start + $range) - 1;
            }
            
            for ($i = $start; $i <= $last; $i++) {
                $this->pages[] = $i;
            }
            
            if ($page <= 1) {
                $this->previousPage = 1;
            } else {
                $this->previousPage = $page - 1;
            }
            
            if ($page >= $this->totalPages) {
                $this->nextPage = $this->totalPages;
            } else {
                $this->nextPage = $page + 1;
            }
        }
    }
}